package be.sc.classicnetwork.service.impl;

import java.util.Collection;
import java.util.Date;

import org.springframework.transaction.annotation.Transactional;

import be.sc.classicnetwork.annotation.RefreshCache;
import be.sc.classicnetwork.dao.GenericDao;
import be.sc.classicnetwork.model.AbstractEntity;
import be.sc.classicnetwork.model.User;
import be.sc.classicnetwork.service.GenericService;

/**
 * Implementation of GenericService holding a GenericDao for CRUD operations.
 */
@Transactional
public class GenericServiceImpl<T extends AbstractEntity> implements
		GenericService<T> {

	private GenericDao<T> dao;

	/**
	 * @param dao
	 */
	public GenericServiceImpl(GenericDao<T> dao) {
		super();
		this.dao = dao;
	}

	/**
	 * @see be.sc.classicnetwork.service.GenericService#countAll()
	 */
	public int countAll() {
		return dao.countAll();
	}

	/**
	 * @see be.sc.classicnetwork.service.GenericService#delete(be.sc.classicnetwork.model.AbstractEntity)
	 */
	@RefreshCache
	public void delete(T entity) {
		dao.delete(entity);
	}

	/**
	 * @see be.sc.classicnetwork.service.GenericService#deleteAll()
	 */
	@RefreshCache
	public void deleteAll() {
		dao.deleteAll();
	}

	/**
	 * @see be.sc.classicnetwork.service.GenericService#findAll(int, int)
	 */
	public Collection<T> findAll(int first, int max) {
		return dao.findAll(first, max);
	}

	/**
	 * @see be.sc.classicnetwork.service.GenericService#findById(int)
	 */
	public T findById(String id) {
		return dao.findById(id);
	}

	/**
	 * @see be.sc.classicnetwork.service.GenericService#findByIdFull(int)
	 */
	public T findByIdFull(String id) {
		return dao.findByIdFull(id);
	}

	/**
	 * @see be.sc.classicnetwork.service.GenericService#saveOrUpdate(be.sc.classicnetwork.model.AbstractEntity)
	 */
	@RefreshCache
	public T saveOrUpdate(T entity) {
		Date now = new Date();

		// set some debug info on the saved entity
		entity.setLastSavedDate(now);
		if (entity.isNew()) {
			entity.setCreatedDate(now);
			entity.setCreatedBy(User.getCurrentUser().getUsername());
		}
		entity.setUserInfo(User.getCurrentUser().getUserInfo());

		// save
		return dao.saveOrUpdate(entity);
	}

	public GenericDao<T> getDao() {
		return dao;
	}

	public void setDao(GenericDao<T> dao) {
		this.dao = dao;
	}

}
